package com.booter.zookeeper.serializer;


import com.booter.zookeeper.exception.ZkMarshallingException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializableSerializer implements ZkSerializer {
    @Override
    public byte[] serialize(Object serializable) {
        if (serializable == null) {
            return null;
        }
        try (UnsafeByteArrayOutputStream byteArrayOS = new UnsafeByteArrayOutputStream();
             ObjectOutputStream stream = new ObjectOutputStream(
                     byteArrayOS)) {
            stream.writeObject(serializable);
            stream.close();
            return byteArrayOS.toByteArray();
        } catch (Exception ex) {
            throw new ZkMarshallingException(ex);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        try (ObjectInputStream os = new ObjectInputStream(
                new UnsafeByteArrayInputStream(bytes))) {
            return os.readObject();
        } catch (ClassNotFoundException e) {
            throw new ZkMarshallingException("Unable to find object class.", e);
        } catch (IOException e) {
            throw new ZkMarshallingException(e);
        }
    }
}
